import { pullData } from '@/api/data'
import { downloadFile, parseTime } from '@/utils'

export default {
  data() {
    return {
      firstInit: true,
      notAutoInitDict: true,
      loading: true,
      data: [],
      url: '',
      params: {},
      query: {},
      sort: 'id,desc',
      time: 50,
      isAdd: false, //Boolean
      downloadLoading: false,
      pagination: {
        current: 1,
        total: 0,
        pageSizeOptions: ['10', '30', '50', '100'],
        showQuickJumper: true,
        showSizeChanger: true,
        showTotal: (total, range) => `${range[0]}-${range[1]}/${total}`
      }
    }
  },
  methods: {
    /**
     * 初始化table数据
     */
    async init() {
      if (this.firstInit && this.notAutoInitDict) {
        await this.initDict()
      }
      if (!(await this.beforeInit())) {
        return
      }
      try {
        this.loading = true
        let res = await pullData(this.url, this.params)
        if (this.pagination) {
          this.pagination.total = res.data.total
        }
        this.data = await this.dataProcessor(res.data.list || res.data)

        setTimeout(() => (this.loading = false), this.time)

        return res
      } catch (err) {
        this.loading = false
        return err
      } finally {
        this.firstInit = false
      }
    },
    /**
     * 数据加载前，this 个性化配置
     */
    beforeInit() {
      return true
    },
    /**
     * 原数据 => table数据 处理
     * @param {Array} data
     */
    dataProcessor(data) {
      return data
    },
    /**
     * 处理 antdv table change事件
     * @param {Object} pagination
     * @param {Object} filters
     * @param {Object} sorter
     */
    handleTableChange(pagination, filters, sorter) {
      if (this.pagination) {
        this.pagination = { ...pagination }
      }
      this.sort = !!sorter.order ? sorter.field + ',' + sorter.order.replace('end', '') : 'id,desc'
      this.init()
    },
    /**
     * 首页查询
     * @param {Object} query
     */
    toQuery(query) {
      if (this.pagination) {
        this.pagination.current = 1
      }
      this.query = query
      this.init()
    },
    /**
     * 最新的查询结果导出
     * 注：csv文件：","逗号换列，\n换行，\t防止excel将长数字变科学计算法等样式
     * @param {Object} query
     */
    async toExport(query) {
      this.downloadLoading = true
      let params = { ...this.params }
      if (this.pagination) {
        params.current = 1
        params.size = this.pagination.total
      }
      try {
        let res = await pullData(this.url, params)
        let data = await this.dataProcessor(res.data.list || res.data)

        let content = []

        let columns = this.columns.filter((e) => e.dataIndex)

        let header = columns.map((e) => e.title).join('\t,')
        content.push(header)

        let dataIndexes = columns.map((e) => e.dataIndex)

        for (let d of data) {
          let temp = []
          for (let di of dataIndexes) {
            temp.push(d[di])
          }
          content.push(temp.join('\t,'))
        }

        downloadFile('\ufeff' + content.join('\n'), this.$options.name, 'csv', { type: 'text/csv,charset=UTF-8' })

        setTimeout(() => (this.downloadLoading = false), this.time)
      } catch (err) {
        this.downloadLoading = false
        return err
      }
    },
    /**
     * 最新的查询结果导出 xlsx csv txt
     *
     * @param {Object} query
     */
    async toExport2(query) {
      this.downloadLoading = true
      let params = { ...this.params }
      if (this.pagination) {
        params.current = 1
        params.size = this.pagination.total
      }
      try {
        let res = await pullData(this.url, params)
        let list = await this.dataProcessor(res.data.list || res.data)

        import('@/vendor/Export2Excel').then((excel) => {
          let columns = this.columns.filter((e) => e.dataIndex)
          const tHeader = columns.map((e) => e.title)
          const filterVal = columns.map((e) => e.dataIndex)
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: this.$options.name,
            autoWidth: true,
            bookType: 'xlsx' || 'csv' || 'txt'
          })
          this.downloadLoading = false
        })
      } catch (err) {
        this.downloadLoading = false
        return err
      }
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map((v) => filterVal.map((j) => v[j]))
    }
  }
}
